<template>
  <!-- 客户信息 -->
  <div>
    <div class="form">
      <el-collapse v-model="activeNames" class="collapse">
        <el-collapse-item title="基本信息" name="1">
          <el-descriptions size="medium" :label-style="labelStyle" :content-style="contentStyle">
            <el-descriptions-item label="客户名称">{{ csmInfo.csmName }}</el-descriptions-item>
            <el-descriptions-item label="客户编号">{{ csmInfo.csmCode }}</el-descriptions-item>
            <el-descriptions-item label="用气性质">{{ formatColumnMap(subTypeAllList, "value", csmInfo.subType, "label") }}</el-descriptions-item>
            <el-descriptions-item label="开户电话">{{ csmInfo.openAccountPhone }}</el-descriptions-item>
            <el-descriptions-item label="身份证姓名">{{ csmInfo.sfzName }}</el-descriptions-item>
            <el-descriptions-item label="身份证号">{{ csmInfo.sfzh }}</el-descriptions-item>
            <el-descriptions-item label="身份证地址">{{ csmInfo.sfzAddress }}</el-descriptions-item>
            <el-descriptions-item v-if="csmInfo.csmType === 2" label="营业执照信息"><span v-if="csmInfo.zzbh">{{ csmInfo.zzbh }}</span></el-descriptions-item>
            <el-descriptions-item label="客户活跃度">{{ csmInfo.label&&formatColumnMap(labelMap, 'value', csmInfo.label, 'desc') }}</el-descriptions-item>
            <el-descriptions-item label="隐患等级">
              <span :class="csmInfo.warnLevel===0?'green':'red'">{{ formatColumnMap(warnLevelMap, "value", csmInfo.warnLevel, "desc") }}</span>
              <el-link v-if="csmInfo.lastCheckId" type="primary" @click="showCheck">（点击查看安检详情）</el-link>
            </el-descriptions-item>
            <el-descriptions-item label="绑定司机">{{ csmInfo.driverName }}</el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">{{ csmInfo.remark }}</el-descriptions-item>
            <el-descriptions-item label="所属机构">{{ csmInfo.nearStationName }}</el-descriptions-item>
            <el-descriptions-item label="组名称">{{ csmInfo.groupName }}</el-descriptions-item>
            <el-descriptions-item label="客户组号">{{ csmInfo.groupCode }}</el-descriptions-item>
            <el-descriptions-item label="组类型">{{ formatColumnMap(groupTypeMap, 'value', csmInfo.groupType, 'desc') }}</el-descriptions-item>
            <!-- <el-descriptions-item label="优惠权益"><el-link type="primary" @click="showPreferential">特价用户（点击查看权益详情）</el-link></el-descriptions-item>
            <el-descriptions-item label="剩余优惠瓶数">0</el-descriptions-item> -->
          </el-descriptions>
        </el-collapse-item>
        <el-collapse-item v-if="csmInfo.preferentialAddressItems && csmInfo.preferentialAddressItems.length > 0" title="优惠权益信息" name="8">
          <el-table :data="csmInfo.preferentialAddressItems" style="width: 100%;" max-height="250">
            <el-table-column prop="csmAddress" label="优惠权益地址" />
            <el-table-column prop="preferentialPackageName" label="权益名称">
              <template slot-scope="{row}">
                <el-link type="primary" @click="showPreferential(row)">{{ row.preferentialPackageName }}</el-link>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
        <el-collapse-item title="一户一码信息" name="2">
          <el-descriptions v-show="csmInfo.qrCode" size="medium" :label-style="labelStyle" :content-style="contentStyle">
            <el-descriptions-item label="一户一码">
              <div style="display: flex;">
                <div style=" margin-right: 10px;">{{ csmInfo.qrCode }}</div>
                <div id="qrcode" ref="qrCodeUrl" style="width: 20px; height: 20px; margin: 0 auto;" @click="creatQrCode1()" />
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="绑定日期">{{ csmInfo.lastBindTime?parseTime(csmInfo.lastBindTime,'{y}-{m}-{d} {h}:{i}:{s}'):'' }}</el-descriptions-item>
            <el-descriptions-item label="省市区">{{ yhymInfo.provinceName }}/{{ yhymInfo.cityName }}/{{ yhymInfo.countryName }}/{{ yhymInfo.streetName }}</el-descriptions-item>
            <el-descriptions-item label="详细地址">{{ yhymInfo.csmAddress }}</el-descriptions-item>
            <el-descriptions-item label="楼层">{{ yhymInfo.csmFloor }}</el-descriptions-item>
            <el-descriptions-item label="门牌号">{{ yhymInfo.doorplate }}</el-descriptions-item>
          </el-descriptions>
        </el-collapse-item>
        <el-collapse-item title="财务信息" name="3">
          <el-descriptions size="medium" :label-style="labelStyle" :content-style="contentStyle">
            <el-descriptions-item label="结款方式">{{ formatColumnMap(statusMap.settlementType, "value", csmInfo.settlementType, "desc") }}</el-descriptions-item>
            <el-descriptions-item label="月结授信额度">{{ csmInfo.decimalSpare2 || csmInfo.decimalSpare2 === 0 ? csmInfo.decimalSpare2 + '元':'' }}</el-descriptions-item>
            <!-- <el-descriptions-item label="结款天数">{{ csmInfo.intSpare2 ? csmInfo.intSpare2 + '天':'' }}</el-descriptions-item> -->
            <el-descriptions-item label="支付方式">{{ formatColumnMap(statusMap.paymentMethod, "value", csmInfo.defaultPaymentMethod, "desc") }}</el-descriptions-item>
            <el-descriptions-item label="客户信用评级"><span class="green">良好</span></el-descriptions-item>
            <el-descriptions-item label="已使用额度">{{ csmInfo.settlementUseMonery || csmInfo.settlementUseMonery === 0 ? csmInfo.settlementUseMonery + '元':'' }}</el-descriptions-item>
            <el-descriptions-item label="待结账款"><span class="blue point" @click="openDetail">{{ csmInfo.totalReceivable ? csmInfo.totalReceivable + '元':'' }}</span></el-descriptions-item>
            <el-descriptions-item label="预付卡卡号"><span class="blue point" @click="changeTab">{{ csmInfo.cardCode }}</span></el-descriptions-item>
            <el-descriptions-item label="开卡日期">{{ csmInfo.cardStartDt ? parseTime(csmInfo.cardStartDt, "{y}/{m}/{d}") :'' }}</el-descriptions-item>
            <el-descriptions-item label="预付卡余额">{{ csmInfo.cardSurplus || csmInfo.cardSurplus === 0 ? (csmInfo.cardSurplus/100).toFixed(2) + '元' : '' }}</el-descriptions-item>
            <el-descriptions-item label="累计储值">{{ csmInfo.totalCardMoney || csmInfo.totalCardMoney === 0 ? (csmInfo.totalCardMoney/100).toFixed(2) + '元':'' }}</el-descriptions-item>
            <el-descriptions-item label="累计消费">{{ csmInfo.totalPayMoney || csmInfo.totalPayMoney === 0 ? (csmInfo.totalPayMoney/100).toFixed(2) + '元':'' }}</el-descriptions-item>
            <el-descriptions-item label="累计消费次数">{{ csmInfo.totalPayCount || csmInfo.totalPayCount === 0 ? csmInfo.totalPayCount + '次':'' }}</el-descriptions-item>
            <el-descriptions-item label="预付卡信用额度">{{ csmInfo.cardFreeMoney || csmInfo.cardFreeMoney === 0 ? (csmInfo.cardFreeMoney/100).toFixed(2) + '元' : '' }}</el-descriptions-item>

          </el-descriptions>
        </el-collapse-item>
        <el-collapse-item title="配送地址信息" name="4">
          <div style="width: 100%;">
            <div v-for="(item, index) in csmInfo.addressItems" :key="index">
              <el-descriptions size="medium" :label-style="labelStyle" :content-style="contentStyle">
                <el-descriptions-item label="联系人姓名">{{ item.contact }}</el-descriptions-item>
                <el-descriptions-item label="联系人电话">{{ item.csmPhone }}</el-descriptions-item>
                <el-descriptions-item label="省市区">{{ item.area }}</el-descriptions-item>
                <el-descriptions-item label="详细地址">{{ item.csmAddress }}</el-descriptions-item>
                <el-descriptions-item label="门牌号">{{ item.doorplate }}</el-descriptions-item>
                <el-descriptions-item label="楼层">{{ item.csmFloor }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </div>
        </el-collapse-item>
        <el-collapse-item title="话务联系人信息" name="5">
          <div v-for="(item, index) in csmInfo.phoneItems" :key="index">
            <el-descriptions size="medium" :label-style="labelStyle" :content-style="contentStyle">
              <el-descriptions-item label="联系人姓名">{{ item.contact }}</el-descriptions-item>
              <el-descriptions-item label="联系人电话">{{ item.csmPhone }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-collapse-item>
        <el-collapse-item title="开户信息" name="6">
          <el-descriptions v-if="csmInfo.newType !== 1 || csmInfo.ownerBottleInfoList.length === 0" size="medium" :label-style="labelStyle" :content-style="contentStyle">
            <el-descriptions-item label="气瓶使用方式">{{ formatColumnMap(statusMap.newType, "value", csmInfo.newType, "desc") }}</el-descriptions-item>
            <el-descriptions-item label="开户日期">{{ csmInfo.createTime ? parseTime(csmInfo.createTime, "{y}/{m}/{d}") : "" }}</el-descriptions-item>
            <el-descriptions-item label="合同号">{{ csmInfo.contractNumber }}</el-descriptions-item>
            <el-descriptions-item label="是否自提">{{ csmInfo.isPickUp ? "是" : "否" }}</el-descriptions-item>
            <el-descriptions-item label="客户来源">{{ formatColumnMap(statusMap.customerFromPlat, "value", csmInfo.newFrom, "desc") }}</el-descriptions-item>
            <el-descriptions-item label="销售人员">{{ csmInfo.salesmanName }}</el-descriptions-item>
            <!-- <el-descriptions-item label="结款方式">{{ formatColumnMap(statusMap.settlementType, "value", csmInfo.settlementType, "desc") }}</el-descriptions-item>
            <el-descriptions-item label="月结授信额度">{{ csmInfo.decimalSpare2 }}</el-descriptions-item>
            <el-descriptions-item label="结款天数">{{ csmInfo.intSpare2 }}</el-descriptions-item>
            <el-descriptions-item label="销户日期">{{ csmInfo.cancelTime ? parseTime(csmInfo.cancelTime, "{y}/{m}/{d}") : "" }}</el-descriptions-item> -->
          </el-descriptions>
          <div v-else>
            <el-descriptions size="medium" :column="1" :label-style="labelStyle" :content-style="contentStyle">
              <el-descriptions-item label="气瓶使用方式">{{ formatColumnMap(statusMap.newType, "value", csmInfo.newType, "desc") }}</el-descriptions-item>
              <el-descriptions-item v-for="(item, index) in csmInfo.ownerBottleInfoList" :key="index" :label="item.goodsName">{{ item.goodsCount }}(瓶)</el-descriptions-item>
            </el-descriptions>
            <el-descriptions size="medium" :label-style="labelStyle" :content-style="contentStyle">
              <el-descriptions-item label="开户日期">{{ csmInfo.createTime ? parseTime(csmInfo.createTime, "{y}/{m}/{d}") : "" }}</el-descriptions-item>
              <el-descriptions-item label="合同号">{{ csmInfo.contractNumber }}</el-descriptions-item>
              <el-descriptions-item label="是否自提">{{ csmInfo.isPickUp ? "是" : "否" }}</el-descriptions-item>
              <el-descriptions-item label="客户来源">{{ formatColumnMap(statusMap.customerFromPlat, "value", csmInfo.newFrom, "desc") }}</el-descriptions-item>
              <el-descriptions-item label="销售人员">{{ csmInfo.salesmanName }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-collapse-item>
        <el-collapse-item title="其他信息" name="7">
          <el-descriptions size="medium" :label-style="labelStyle" :content-style="contentStyle">
            <el-descriptions-item label="使用权费">{{ csmInfo.strSpare1 }}</el-descriptions-item>
            <el-descriptions-item label="备用字段2">{{ csmInfo.strSpare2 }}</el-descriptions-item>
            <el-descriptions-item label="备用字段3">{{ csmInfo.strSpare3 }}</el-descriptions-item>
            <el-descriptions-item label="备用字段4">{{ csmInfo.strSpare4 }}</el-descriptions-item>
          </el-descriptions>
        </el-collapse-item>
      </el-collapse>
      <security-order-info
        ref="securityOrderInfo"
        :tree-data="treeData"
      />
      <SettlementDialog ref="settlementDialogRef" />
      <preferentialUser ref="preferentialUser" />
      <el-dialog
        title="二维码"
        :visible.sync="qrcodeShow"
        append-to-body
        width="300px"
        center
      >
        <div>
          <div id="qrcode1" ref="qrCodeUrl1" style="width: 200px; height: 200px; margin: 0 auto;" />
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import { querySubTypeMap, queryAddCsmDefaultData, queryRiskTrackMap, customerAttachment } from '@/api'
  import { parseTime, formatColumnMap } from '@/utils'
  import getTreeData from '@/utils/jsonTree'
  import SettlementDialog from '../../financialManage/accountMonthManage/components/SettlementDialog.vue'
  import preferentialUser from './preferentialUser'
  import { mapGetters } from 'vuex'
  import QRCode from 'qrcodejs2'
  export default {
    name: 'tabUser',
    components: {
      securityOrderInfo: () => import('../../safetySupervise/securityOrderManage/components/securityOrderInfo.vue'),
      preferentialUser,
      SettlementDialog
    },
    props: {
      csmInfo: {
        type: Object,
        required: true
      },
      groupTypeMap: {
        type: Array,
        required: true
      },
      labelMap: {
        type: Array,
        default: () => [],
        required: true
      }
    },
    data() {
      return {
        parseTime: parseTime,
        activeNames: ['1', '2', '3', '4', '8'],
        activeTabName: 'customer',
        statusMap: {},
        subTypeAllList: [],
        yhymInfo: {},
        qrcodeShow: false, // 二维码展示
        labelStyle: { 'white-space': 'nowrap' },
        contentStyle: { 'word-break': 'break-all' },
        warnLevelMap: [],
        treeData: [],
        preferentialData: [
          {
            address: '111111',
            name: '2',
            num: 0
          },
          {
            address: '111111',
            name: '2',
            num: 1
          },
          {
            address: '111111',
            name: '2',
            num: 2
          },
          {
            address: '111111',
            name: '2',
            num: 0
          },
          {
            address: '111111',
            name: '2',
            num: 1
          },
          {
            address: '111111',
            name: '2',
            num: 2
          },
          {
            address: '111111',
            name: '2',
            num: 0
          },
          {
            address: '111111',
            name: '2',
            num: 1
          },
          {
            address: '111111',
            name: '2',
            num: 2
          }
        ]
      }
    },
    computed: {
      ...mapGetters(['orgList'])
    },
    watch: {
      csmInfo: {
        handler(options) {
          this.initData(this.options)
        },
        deep: true
      }
    },
    mounted() {
      this.initData()
      this.getTreeData()
    },
    methods: {
      creatQrCode(url) {
        this.$refs.qrCodeUrl.innerHTML = ''
        new QRCode(this.$refs.qrCodeUrl, {
          text: url,
          width: 20,
          height: 20,
          colorDark: '#000000',
          colorLight: '#ffffff',
          correctLevel: QRCode.CorrectLevel.H
        })
      },
      creatQrCode1() {
        const url = `${this.csmInfo.qrCodeImageUrl}/${this.csmInfo.qrCode}`
        this.qrcodeShow = true
        setTimeout(() => {
          this.$refs.qrCodeUrl1.innerHTML = ''
          new QRCode(this.$refs.qrCodeUrl1, {
            text: url,
            width: 200,
            height: 200,
            colorDark: '#000000',
            colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.H
          })
        }, 500)
      },
      formatColumnMap,
      initData() {
        this.initAddress()
        this.getStatusMap()
        this.getdanger()
        this.customerAttachment()
        const box = this.csmInfo.addressItems.filter(item => item.csmAddressId === this.csmInfo.csmAddressId)
        this.yhymInfo = box[0] || {}
        this.creatQrCode(`${this.csmInfo.qrCodeImageUrl}/${this.csmInfo.qrCode}`)
      },
      async customerAttachment() {
        const res = await customerAttachment({ csmCode: this.csmInfo.csmCode })
        this.cardList = res.data.cardItems
        const zzbh = []
        this.cardList.forEach((item) => {
          if (item.cardType === 4) {
            zzbh.push(item.cardNo)
          }
        })
        this.$set(this.csmInfo, 'zzbh', zzbh.join(','))
      },
      async getStatusMap() {
        const res = await queryAddCsmDefaultData()
        var obj = {}
        for (var value in res.data) {
          if (this.isJsonString(res.data[value])) {
            var item = JSON.parse(res.data[value])
            obj[value] = item
          }
        }
        this.statusMap = obj
        const res1 = await querySubTypeMap({ })
        this.subTypeAllList = res1.data
        // console.log(this.statusMap)
      },
      // 判断是否为JSON对象
      isJsonString(str) {
        try {
          if (typeof JSON.parse(str) === 'object') {
            return true
          }
        } catch (e) {
          console.log()
        }
        return false
      },
      initAddress() {
        this.csmInfo.addressItems.forEach((item) => {
          item.area = item.provinceName + '/' + item.cityName + '/' + item.countryName + '/' + (item.streetName ? item.streetName : '')
        })
      },
      // 查询隐患等级
      async getdanger() {
        // presetDicQueryList
        const res = await queryRiskTrackMap()
        const data = JSON.parse(res.data.warnLevel) // 隐患等级
        if (data) {
          this.warnLevelMap = []
          data.forEach(item => {
            this.warnLevelMap.push({
              value: item.keyVal,
              desc: item.keyName
            })
          })
          this.warnLevelMap.push({
            value: 0,
            desc: '无隐患'
          })
        }
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      showCheck() {
        const securityDom = document.getElementsByClassName('security')[0]
        if (!securityDom) {
          this.csmInfo.checkId = this.csmInfo.lastCheckId
          this.$refs.securityOrderInfo.open(this.csmInfo, '安检信息')
        } else {
          this.$message.warning('该信息弹窗已存在，请关闭当前弹窗')
        }
      },
      // 查看特价用户权益
      showPreferential(row) {
        this.$refs.preferentialUser.open(row)
      },
      // 查看对账单详情
      openDetail() {
        const orderInfo = {
          csmCode: this.csmInfo.csmCode,
          csmName: this.csmInfo.csmName,
          csmPhone: this.csmInfo.csmRgPhone,
          csmId: this.csmInfo.csmId,
          orgId: this.csmInfo.orgId,
          orgSNNo: this.csmInfo.orgSNNo
        }
        this.$refs['settlementDialogRef'].show(1, orderInfo)
      },
      // tab切换到充值记录
      changeTab() {
        this.$emit('changeTab', 'recharge')
      }
    }
  }
</script>

<style lang='scss' scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  .collapse {
    width: 100%;
    /deep/ .el-collapse-item__header {
      font-size: 14px;
      font-weight: 700;
      color: #38BDBD;
    }
    /deep/ .el-collapse-item__content {
      padding-bottom: 10px;
    }
  }
}
.green {
  color: #67C23A;
}
.red {
  color: #F56C6C;
}
.blue {
  color: #409EFF;
}
.point {
  cursor: pointer;
}
</style>
